package com.cj.mobile.iabp.mvp.presenter;

import static com.cj.mobile.iabp.BuildConfig.IS_DEBUG_DATA;

import android.os.Bundle;
import android.text.TextUtils;

import com.cj.mobile.iabp.app.config.CommonRetryWithDelay;
import com.cj.mobile.iabp.app.global.Constant;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.CompressImage;
import com.cj.mobile.iabp.app.utils.RxUtils;
import com.cj.mobile.iabp.mvp.contract.AddRemoveInfoContract;
import com.cj.mobile.iabp.mvp.model.entity.RemoveInfo;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 2025/09/29 16:25
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class AddRemoveInfoPresenter extends BasePresenter<AddRemoveInfoContract.Model, AddRemoveInfoContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;

    // 患者id
    private String id;
    // 患者登记号
    private String code;
    // 患者姓名
    private String name;
    // 医生id
    private String doctorId;
    // 科室id
    private String deptId;
    // 院区
    private String deptSec;
    // 修改撤机信息的数据源
    private RemoveInfo info;
    // 是否修改
    private boolean isModify;
    // 撤机id
    private String removeId;

    // 拍照图片(本地)
    private ArrayList<String> takePicturesImgs;
    private ArrayList<String> updateImgs;

    @Inject
    public AddRemoveInfoPresenter(AddRemoveInfoContract.Model model, AddRemoveInfoContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.takePicturesImgs = null;
        this.updateImgs = null;
    }

    public void getBundleValues(Bundle bundle) {
        if (bundle != null) {
            id = bundle.getString("id");
            code = bundle.getString("code");
            name = bundle.getString("name");

            doctorId = bundle.getString("doctorId");
            deptId = bundle.getString("deptId");
            deptSec = bundle.getString("deptSec");

            info = bundle.getParcelable("info");
            if (info != null)
                removeId = info.getId();
        }
        isModify = info != null;
    }

    public void initData(Bundle bundle) {
        getBundleValues(bundle);

        takePicturesImgs = new ArrayList<>();
        updateImgs = new ArrayList<>();

        // 显示登记号和患者姓名
        mRootView.showRemoveInfo(code, name, info);
    }

    /**
     * 计算运行时间
     */
    public void computeRunTime(String time) {
        if (IS_DEBUG_DATA) {
            mRootView.loadRunTime("1985小时");
        } else {
            mModel.getRunTime(id, time)
                    .compose(RxUtils.applySchedulers(mRootView)) // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {

                        @Override
                        public void onNext(String date) {
                            mRootView.loadRunTime(date);

                        }
                    });
        }
    }


    /**
     * 提交事件
     *
     * @param pre         暂存0或提交1
     * @param regCode     注册代码
     * @param removeType  撤机类型
     * @param removeTime  撤机时间
     * @param runTimeStr  运行时间
     * @param focuse      关注
     * @param isAlive     撤机患者状态
     * @param moreDiag    并发症
     * @param moreDiagTxt 并发症中其它选项的文字描述
     */
    public void btnSubmit(String pre, String regCode, String removeType, String removeTime, String runTimeStr,
                          String focuse, String isAlive, String moreDiag, String moreDiagTxt, List<String> files) {
        if (IS_DEBUG_DATA) {
            mRootView.showMessage("信息维护成功！");
        } else {

            if (isModify) {
                // 修改撤机信息

                // “mImgs”中存在混合图(既有网上的，又有拍照的)，特殊处理：将“mImgs”逐条过滤成两个变量。
                // 然后 “拍照的” 单独上传，上传成功后做一次合并。然后再提交数据。
                filterImg(files);

                if (CommonUtils.isNotEmpty(takePicturesImgs)) {
                    compressImage(takePicturesImgs, path -> {
                        mModel.upload(path)
                                .subscribeOn(Schedulers.io())
                                .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                                .doOnSubscribe(disposable -> {
                                    mRootView.showLoadingSubmit();
                                })
                                .subscribeOn(AndroidSchedulers.mainThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .doFinally(() -> {
                                }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                                .flatMap((Function<List<String>, ObservableSource<Integer>>) infoResponse -> {
                                    // 合并图片
                                    infoResponse.addAll(updateImgs);
                                    // 更新接口
                                    return mModel.updateRemove(pre, removeId, id, doctorId, deptId, deptSec,
                                                    regCode, name, removeType, removeTime, runTimeStr,
                                                    focuse, isAlive, moreDiag, moreDiagTxt, infoResponse)
                                            .subscribeOn(Schedulers.io())
                                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                                            .doOnSubscribe(disposable -> {
                                            })
                                            .subscribeOn(AndroidSchedulers.mainThread())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .doFinally(() -> {
                                                mRootView.hideLoadingSubmit();
                                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView));                            // 切换线程

                                })
                                .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                    @Override
                                    public void onNext(Integer commonResponse) {
                                        mRootView.showMessage("修改成功！");
                                        mRootView.killMyself();
                                    }
                                });
                    });
                } else {
                    // 基本信息
                    mModel.updateRemove(pre, removeId, id, doctorId, deptId, deptSec,
                                    regCode, name, removeType, removeTime, runTimeStr,
                                    focuse, isAlive, moreDiag, moreDiagTxt, null)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                                mRootView.hideLoadingSubmit();
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    mRootView.showMessage("修改成功！");
                                    mRootView.killMyself();
                                }
                            });
                }
            } else {
                // 新增撤机信息
                if (CommonUtils.isNotEmpty(files)) {
                    // 压缩图片
                    compressImage(files, path -> {

                        // 执行上传操作
                        mModel.upload(path)
                                .subscribeOn(Schedulers.io())
                                .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                                .doOnSubscribe(disposable -> {
                                    mRootView.showLoadingSubmit();
                                })
                                .subscribeOn(AndroidSchedulers.mainThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .doFinally(() -> {
                                }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                                .flatMap((Function<List<String>, ObservableSource<Integer>>) infoResponse -> {

                                    // 更新接口
                                    return mModel.addRemove(pre, id, doctorId, deptId, deptSec,
                                                    regCode, name, removeType, removeTime, runTimeStr,
                                                    focuse, isAlive, moreDiag, moreDiagTxt, infoResponse)
                                            .subscribeOn(Schedulers.io())
                                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                                            .doOnSubscribe(disposable -> {
                                            })
                                            .subscribeOn(AndroidSchedulers.mainThread())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .doFinally(() -> {
                                                mRootView.hideLoadingSubmit();
                                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView));                            // 切换线程

                                })
                                .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                    @Override
                                    public void onNext(Integer commonResponse) {
                                        mRootView.showMessage("保存成功！");
                                        mRootView.killMyself();
                                    }
                                });
                    });

                } else {
                    // 基本信息
                    mModel.addRemove(pre, id, doctorId, deptId, deptSec,
                                    regCode, name, removeType, removeTime, runTimeStr,
                                    focuse, isAlive, moreDiag, moreDiagTxt, null)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                                mRootView.hideLoadingSubmit();
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    mRootView.showMessage("保存成功！");
                                    mRootView.killMyself();
                                }
                            });
                }
            }
        }
    }

    /**
     * 压缩图片
     */
    private void compressImage(List<String> mImg, CompressImage callback) {
        // 压缩好的图片
        ArrayList<String> newPath = new ArrayList<>();

        Luban.with(mRootView.getActivity())
                .load(mImg)
                .ignoreBy(500)
                .setTargetDir(Constant.IMAGE_PATH)
                .filter(path1 -> !(TextUtils.isEmpty(path1) || path1.toLowerCase().endsWith(".gif")))
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                        mRootView.showLoadingSubmit();
                    }

                    @Override
                    public void onSuccess(File file) {
                        // 压缩成功后调用，返回压缩后的图片文件
                        newPath.add(file.getAbsolutePath());

                        // 全部压缩完后，执行上传
                        if (mImg.size() == newPath.size())
                            if (callback != null) {
                                callback.success(newPath);
                            }

                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                        mRootView.showMessage("图片压缩过程出现问题：" + e.getMessage());
                        mRootView.hideLoadingSubmit();
                    }
                }).launch();
    }

    /**
     * 图片过滤
     */
    private void filterImg(List<String> mImgs) {
        takePicturesImgs.clear();
        updateImgs.clear();
        for (String str : mImgs) {
            if (str.contains("http")) {
                // 网络原有的
                updateImgs.add(str);
            } else {
                // 本地的
                takePicturesImgs.add(str);
            }
        }
    }
}